package 数组;

import java.util.Arrays;

public class LC_059螺旋矩阵 {
    public static void main(String[] args){
        int n=3;
        System.out.println(Arrays.deepToString(generateMatrix(n)));
    }
    public static int[][] generateMatrix(int n) {
        int[][] res=new int[n][n];
        int top=0,bottom=n-1,left=0,right=n-1,count=1;
        while(count<=n*n && top<=bottom && left<=right){
            for(int i=0;i<right-left;i++){//从左往右
                res[top][left+i]=count;
                count++;
            }
            for(int i=0;i<bottom-top;i++){//从上往下
//                res[right][top+i]=count;
                res[top+i][right]=count;
                count++;
            }
            for(int i=0;i<right-left;i++){//从右往左
                res[bottom][right-i]=count;
                count++;
            }
            for(int i=0;i<bottom-top;i++){//从下往上
                res[bottom-i][left]=count;
                count++;
            }
            if(left==right && top==bottom){//只有一个元素
                res[top][left]=count;
                return res;
            }
            top++;
            left++;
            right--;
            bottom--;
        }

        return res;
    }
}
